/**
 * Alipay.com Inc.
 * Copyright (c) 2009-2010 All Rights Reserved.
 */
package com.alipay.test.dbtest.operation;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.lang.ArrayUtils;
import org.dbunit.DatabaseUnitException;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.operation.DatabaseOperation;

import com.alipay.test.dbtest.script.DDLScriptExecuter;
import com.alipay.test.dbtest.script.ScriptException;
import com.alipay.test.dbtest.script.ScriptLoaderToExecuterAdapter;

/**
 * 
 * 
 * @author quickpoint
 * @version $Id: SetUpDatabaseOperation.java, v 0.1 2010-5-29 下午11:04:51 quickpoint Exp $
 */
public class ScriptDatabaseOperation extends DatabaseOperation {

    private String[] scripts;

    public ScriptDatabaseOperation(String[] scripts) {
        this.scripts = scripts;
    }

    /* (non-Javadoc)
     * @see org.dbunit.operation.DatabaseOperation#execute(org.dbunit.database.IDatabaseConnection, org.dbunit.dataset.IDataSet)
     */
    @Override
    public void execute(IDatabaseConnection connection, IDataSet dataSet)
                                                                         throws DatabaseUnitException,
                                                                         SQLException {

        if (ArrayUtils.isEmpty(scripts)) {
            // no script for execute
            return;
        }
        Connection dbCon = connection.getConnection();
        ScriptLoaderToExecuterAdapter runner = new ScriptLoaderToExecuterAdapter();
        runner.setScriptExecuter(new DDLScriptExecuter(dbCon));
        try {
            for (String script : scripts) {
                runner.load(script);
            }
        } catch (ScriptException ex) {
            throw new DatabaseUnitException(ex);
        }
    }

}
